package com.hhit.bigscreenbackmanage.service.impl;

import com.hhit.bigscreenbackmanage.dao.jjgl.TJjglJjxmyszxMapper;
import com.hhit.bigscreenbackmanage.entity.jjgl.TJjglJjxmyszxEntity;
import com.hhit.bigscreenbackmanage.service.ImportService;
import com.hhit.bigscreenbackmanage.util.DateUtilRewrite;
import com.hhit.bigscreenbackmanage.util.ImportPathUitls;
import com.hhit.bigscreenbackmanage.util.PropertiesUtils;
import com.hhit.bigscreenbackmanage.util.Utils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ImportServiceImpl implements ImportService {

    private final String path = "D:\\javatest\\";

    @Autowired
    private TJjglJjxmyszxMapper tJjglJjxmyszxMapper;

    @Override
    public Map<String, Object> importDataEveryMonth() throws Exception {
        Map result = new HashMap();
        String realPath;
        File file = new File(path);
        Calendar rightNow = Calendar.getInstance();
        Integer year = rightNow.get(Calendar.YEAR);
        Integer month = rightNow.get(Calendar.MONTH) + 1;
        String timePath;
        if (month < 10) {
            timePath = year + "0" + month;
        } else {
            timePath = String.valueOf(year) + String.valueOf(month);
        }
        if (file.exists()) {
            //获取根目录下面所有文件夹的名称，即页面模块的名称
            String[] names = file.list();
            for (int i = 0; i < names.length; i++) {
                String name = names[i];
                realPath = path + name + "\\" + timePath;
                File file1 = new File(realPath);
                //判断是否存在当前月份所存在的文件夹
                if (file1.exists()) {
                    File[] array = file1.listFiles();
                    for (int j = 0; j < array.length; j++) {
                        if (array[j].isFile()) {
                            String fileName = array[j].getName();
                            String filepath = realPath + "\\" + fileName;
                            //需要判断数据苦衷是否存在需要导入月份的数据
                            if (false) {

                            }
                            List<Map<String, Object>> excellist = getExcelDataForGis(fileName, filepath);
                            if (excellist.size() > 0) {
                                List<TJjglJjxmyszxEntity> list = (List<TJjglJjxmyszxEntity>) Utils.mapToEntiry(excellist, TJjglJjxmyszxEntity.class);
                                int count = tJjglJjxmyszxMapper.importTJjglJjxmyszx(list);
                                if (count > 0) {
                                    System.out.println("文件：" + filepath + "，已成功导入");
                                    result.put("flag", true);
                                }
                            }
                        }
                    }

                } else {
                    System.out.println("不存在：" + realPath + "这个文件夹");
                    continue;
                }
            }
        } else {
            System.out.println("不存在：" + path + "这个文件夹");
            result.put("flag", false);
        }
        return result;
    }

    @Override
    public Map checkDataEveryMonth(String param) throws Exception {
        Map result = new HashMap();
        //初始化的时候，检测全部
        if ("".equals(param)) {
            //初设评审计划执行
            File cspsjhFile = new File(ImportPathUitls.jjgl_cspsjh);
            File[] cspsjhFiles = cspsjhFile.listFiles();
            if (cspsjhFiles.length > 0) {
                int count1 = tJjglJjxmyszxMapper.checkCspsjhMonthData();
                int count2 = tJjglJjxmyszxMapper.checkNdjhMonthData();
                if (count1 == 0&&count2==0) {
                    result.put("cspsjhSign", "1");
                    result.put("cspsjh", ImportPathUitls.jjgl_cspsjh + "文件夹中的数据可以进行导入操作。");
                } else if(count1 == 0 && count2 != 0){
                    result.put("cspsjhSign", "0");
                    result.put("cspsjh", ImportPathUitls.jjgl_cspsjh + "“初设评审计划执行年度计划”的数据已导入过数据。");
                }else  if(count1 != 0 && count2 == 0){
                    result.put("cspsjhSign", "0");
                    result.put("cspsjh", ImportPathUitls.jjgl_cspsjh + "“初设评审计划执行”的数据已导入过数据。");
                }else {
                    result.put("cspsjhSign", "0");
                    result.put("cspsjh", ImportPathUitls.jjgl_cspsjh + "“初设评审计划执行和年度计划”的数据已导入过数据。");
                }
            } else {
                result.put("cspsjh", ImportPathUitls.jjgl_cspsjh + "目录下不存在需要导入的文件");
            }
            //规模及以下初设评审意见出具
            File gmjyxcspsyjcjFile = new File(ImportPathUitls.jjgl_gmjyxcspsyjcj);
            File[] gmjyxcspsyjcjFiles = gmjyxcspsyjcjFile.listFiles();
            if (gmjyxcspsyjcjFiles.length > 0) {
                int count = tJjglJjxmyszxMapper.checkCspsjhMonthData();//和“初设评审计划执行”用的一张表
                if (count == 0) {
                    result.put("gmjyxcspsyjcjSign", "1");
                    result.put("gmjyxcspsyjcj", ImportPathUitls.jjgl_gmjyxcspsyjcj + "文件夹中的数据可以进行导入操作。");
                } else {
                    result.put("gmjyxcspsyjcjSign", "0");
                    result.put("gmjyxcspsyjcj", ImportPathUitls.jjgl_gmjyxcspsyjcj + "“规模及以下初设评审意见出具”的数据已导入过数据。");
                }
            } else {
                result.put("gmjyxcspsyjcj", ImportPathUitls.jjgl_gmjyxcspsyjcj + "目录下不存在需要导入的文件");
            }
            //概算估算偏差
            File gsgspcFile = new File(ImportPathUitls.jjgl_gsgspc);
            File[] gsgspcFiles = gsgspcFile.listFiles();
            if (gsgspcFiles.length > 0) {
                int count = tJjglJjxmyszxMapper.checkCspsjhMonthData();//和“初设评审计划执行”用的一张表
                if (count == 0) {
                    result.put("gsgspcSign", "1");
                    result.put("gsgspc", ImportPathUitls.jjgl_gsgspc + "文件夹中的数据可以进行导入操作。");
                } else {
                    result.put("gsgspcSign", "0");
                    result.put("gsgspc", ImportPathUitls.jjgl_gsgspc + "“规模及以下初设评审意见出具”的数据已导入过数据。");
                }
            } else {
                result.put("gsgspc", ImportPathUitls.jjgl_gsgspc + "目录下不存在需要导入的文件");
            }
            //施工图预算
            File sgtysFile = new File(ImportPathUitls.jjgl_sgtys);
            File[] sgtysFiles = sgtysFile.listFiles();
            if (sgtysFiles.length > 0) {
                //前台写死
            } else {
                result.put("sgtys", ImportPathUitls.jjgl_sgtys + "目录下不存在需要导入的文件");
            }
            //基建项目预算执行
            File jjxmyszxFile = new File(ImportPathUitls.jjgl_jjxmyszx);
            File[] jjxmyszxFiles = jjxmyszxFile.listFiles();
            if (jjxmyszxFiles.length > 0) {
                int count = tJjglJjxmyszxMapper.checkMonthData();
                if (count == 0) {
                    result.put("jjxmyszxSign", "1");
                    result.put("jjxmyszx", ImportPathUitls.jjgl_jjxmyszx + "文件夹中的数据可以进行导入操作。");
                } else {
                    result.put("jjxmyszxSign", "0");
                    result.put("jjxmyszx", ImportPathUitls.jjgl_jjxmyszx + "“基建项目预算执行”的数据已导入过数据。");
                }
            } else {
                result.put("jjxmyszxSign", "0");
                result.put("jjxmyszx", ImportPathUitls.jjgl_jjxmyszx + "目录下不存在需要导入的文件");
            }
            //尾工管理
            File wgglFile = new File(ImportPathUitls.jjgl_wggl);
            File[] wgglFiles = wgglFile.listFiles();
            if (wgglFiles.length > 0) {
                int count1 = tJjglJjxmyszxMapper.checkWgglmxMonthData();
                int count2 = tJjglJjxmyszxMapper.checkWggltjMonthData();
                if (count1 == 0 && count2 == 0) {
                    result.put("wgglSign", "1");
                    result.put("wggl", ImportPathUitls.jjgl_wggl + "文件夹中的数据可以进行导入操作。");
                } else if(count1 == 0 && count2 != 0){
                    result.put("wgglSign", "0");
                    result.put("wggl", ImportPathUitls.jjgl_wggl + "“尾工管理统计”的数据已导入过数据。");
                } else if(count1 != 0 && count2 == 0){
                    result.put("wgglSign", "0");
                    result.put("wggl", ImportPathUitls.jjgl_wggl + "“尾工管理明细”的数据已导入过数据。");
                }else {
                    result.put("wgglSign", "0");
                    result.put("wggl", ImportPathUitls.jjgl_wggl + "“尾工管理”的数据已导入过数据。");
                }
            } else {
                result.put("wggl", ImportPathUitls.jjgl_wggl + "目录下不存在需要导入的文件");
            }

            File ssdbFile = new File(ImportPathUitls.jjgl_ssdb);
            File[] ssdbFiles = ssdbFile.listFiles();
            if (ssdbFiles.length > 0) {

            } else {
                result.put("ssdb", ImportPathUitls.jjgl_ssdb + "目录下不存在需要导入的文件");
            }

            File jgjsFile = new File(ImportPathUitls.jjgl_jgjs);
            File[] jgjsFiles = jgjsFile.listFiles();
            if (jgjsFiles.length > 0) {

            } else {
                result.put("jgjs", ImportPathUitls.jjgl_jgjs + "目录下不存在需要导入的文件");
            }

            File glgzFile = new File(ImportPathUitls.jjgl_glgz);
            File[] glgzFiles = glgzFile.listFiles();
            if (glgzFiles.length > 0) {

            } else {
                result.put("glgz", ImportPathUitls.jjgl_glgz + "目录下不存在需要导入的文件");
            }
        } else {

        }

        return result;
    }

    public static List<Map<String, Object>> getExcelDataForGis(String fileName, String filepath) throws Exception {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        List<Map<String, Object>> resultList = new ArrayList<>();
        InputStream is = null;
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            System.out.println("文件格式不正确");
        } else {
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            Sheet sheet = null;
            if (isExcel2003) {
                is = new FileInputStream(filepath);
                HSSFWorkbook wb = new HSSFWorkbook(is);
                sheet = wb.getSheetAt(0);
            } else {
                is = new FileInputStream(filepath);
                XSSFWorkbook wb = new XSSFWorkbook(is);
                sheet = wb.getSheetAt(0);
            }
            //校验文件是否为空
            if (sheet.getLastRowNum() > 0) {
                List<String> keyValueList = columnName("jjxmyszxColumnName");//列值
                if (keyValueList.size() > 0) {
                    int rowNumber = 0;
                    //外层循环判读数据读取的起始位置
                    for (int r = 0; r <= sheet.getLastRowNum(); r++) {
                        Row row = sheet.getRow(r);
                        rowNumber++;
                        String cellValue = "";
                        //将单元格每一行的第一个单元格的数据类型设置成String
                        if (row != null && row.getCell(0) != null) {
                            row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                            //获取每一行的第一个单元格的数据
                            cellValue = row.getCell(0).getStringCellValue();
                        }
                        //判断序号为1的时候然后开始读取剩余行的数据
                        if (cellValue.equals("1") || cellValue.equals("1.0")) {
                            int targetRowNumber = rowNumber - 1;
                            //中间循环 读取行
                            for (int r1 = targetRowNumber; r1 <= sheet.getLastRowNum(); targetRowNumber++) {
                                Row row1 = sheet.getRow(targetRowNumber);
                                if (row1 == null) {
                                    break;
                                }
                                if (row1 != null) {
                                    if (row1.getCell(0) == null) {
                                        System.out.println(row1);
                                    } else {
                                        row1.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                                    }
                                }
                                //只录取每行第一个单元格有序号的数据
                                if (row1.getCell(0) != null) {
                                    if (!"".equals((row1.getCell(0).getStringCellValue()))) {
                                        Map<String, Object> rmap = new HashMap<>();
                                        //内层循环 读取列
                                        for (int k = 0; k < keyValueList.size(); k++) {
                                            if (row1.getCell(k) != null) {
                                                Cell cell = row1.getCell(k);
                                                int cellType = cell.getCellType();
                                                String targetCellValue = null;
                                                switch (cellType) {
                                                    case Cell.CELL_TYPE_STRING: //文本
                                                        targetCellValue = cell.getStringCellValue();
                                                        break;
                                                    case Cell.CELL_TYPE_NUMERIC: //数字、日期
                                                        if (DateUtilRewrite.isCellDateFormatted(cell)) {
                                                            targetCellValue = fmt.format(cell.getDateCellValue()); //日期型
                                                        } else {
                                                            //数字
                                                            String formatType = cell.getCellStyle().getDataFormatString() == null ? "" : cell.getCellStyle().getDataFormatString();
                                                            if (formatType.indexOf("%") != -1) {
                                                                double numericCellValue = cell.getNumericCellValue();
                                                                boolean fuShu = false;
                                                                if (numericCellValue < 0) {
                                                                    fuShu = true;
                                                                    numericCellValue = -numericCellValue;
                                                                }
                                                                int baifenshuxiaoshuwei = 0;
                                                                if (formatType.indexOf(".") != -1) {
                                                                    baifenshuxiaoshuwei = formatType.substring(formatType.indexOf("."), formatType.indexOf("%")).length() - 1; // 获取小数位数
                                                                    targetCellValue = "#.";
                                                                    for (int weishu = 0; weishu < baifenshuxiaoshuwei; weishu++) {
                                                                        targetCellValue += "0";
                                                                    }
                                                                    targetCellValue = new DecimalFormat(targetCellValue).format(numericCellValue * 100) + "%";
                                                                    if (targetCellValue.startsWith(".")) {// 如果以.开头的，前面加0拼接；
                                                                        targetCellValue = "0" + targetCellValue;
                                                                    }
                                                                } else {
                                                                    targetCellValue = Math.round(numericCellValue * 100) + "%";
                                                                }
                                                                if (fuShu) {
                                                                    targetCellValue = "-" + targetCellValue;
                                                                }
                                                            } else {
                                                                cell.setCellType(Cell.CELL_TYPE_STRING);
                                                                targetCellValue = cell.getStringCellValue();
                                                            }
                                                        }
                                                        break;
                                                    case Cell.CELL_TYPE_BOOLEAN: //布尔型
                                                        targetCellValue = String.valueOf(cell.getBooleanCellValue());
                                                        break;
                                                    case Cell.CELL_TYPE_BLANK: //空白
                                                        targetCellValue = cell.getStringCellValue();
                                                        break;
                                                    case Cell.CELL_TYPE_ERROR: //错误
                                                        targetCellValue = "错误";
                                                        break;
                                                    case Cell.CELL_TYPE_FORMULA: //公式
                                                        //尾工管理那个函数日期用
                                                        //targetCellValue = fmt.format(cell.getDateCellValue());
                                                        //targetCellValue = "错误";
                                                        try {
                                                            String formatType = cell.getCellStyle().getDataFormatString();
                                                            if (formatType.indexOf("%") != -1) {
                                                                double numericCellValue = cell.getNumericCellValue();
                                                                boolean fuShu = false;
                                                                if (numericCellValue < 0) {
                                                                    fuShu = true;
                                                                    numericCellValue = -numericCellValue;
                                                                }
                                                                int baifenshuxiaoshuwei = 0;
                                                                if (formatType.indexOf(".") != -1) {
                                                                    baifenshuxiaoshuwei = formatType.substring(formatType.indexOf("."), formatType.indexOf("%")).length() - 1; // 获取小数位数
                                                                    targetCellValue = "#.";
                                                                    for (int weishu = 0; weishu < baifenshuxiaoshuwei; weishu++) {
                                                                        targetCellValue += "0";
                                                                    }
                                                                    targetCellValue = new DecimalFormat(targetCellValue).format(numericCellValue * 100) + "%";
                                                                    if (targetCellValue.startsWith(".")) {// 如果以.开头的，前面加0拼接；
                                                                        targetCellValue = "0" + targetCellValue;
                                                                    }
                                                                } else {
                                                                    targetCellValue = Math.round(numericCellValue * 100) + "%";
                                                                }
                                                                if (fuShu) {
                                                                    targetCellValue = "-" + targetCellValue;
                                                                }
                                                            } else {
                                                                targetCellValue = String.valueOf(cell.getNumericCellValue());
                                                            }
                                                        } catch (IllegalStateException e) {
                                                            targetCellValue = String.valueOf(cell.getRichStringCellValue());
                                                        }
                                                        break;
                                                    default:
                                                        targetCellValue = "错误";
                                                }
                                                //存储每个单元格数据
                                                rmap.put(keyValueList.get(k), targetCellValue);
                                            }
                                        }
                                        resultList.add(rmap);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return resultList;
    }

    public static List<String> columnName(String nameAndValue) {
        List<String> resultList = new ArrayList<>();
        Properties p = PropertiesUtils.getPropertys();
        if (nameAndValue.endsWith("Name")) {
            String[] result = p.getProperty(nameAndValue).split(",");
            for (String s : result) {
                resultList.add(s);
            }
        } else if (nameAndValue.endsWith("Value")) {
            String[] result = p.getProperty(nameAndValue).split(",");
            for (String s : result) {
                resultList.add(s);
            }
        }
        return resultList;
    }
}
